import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class FileWriterReaderDemo {
	public static void main(String[] args) {
		
		FileWriterReaderDemo fileWriterReaderDemo=new FileWriterReaderDemo();
		//fileWriterReaderDemo.readFile();
		
		fileWriterReaderDemo.listFiles();
		FileWriter fileWriter=null;
		
		try {
       File file=new File("/home/rajeev/vikas/file.txt");
		
         if(file.exists()){
        	 System.out.println("file deleted succesflly.");
        	 file.delete();
         }
       
         file.createNewFile();
         
         
        file.setExecutable(true);
        file.setWritable(true);
        
        
			
			fileWriter=new  FileWriter(file,true);
		
			fileWriter.write("\n Hello this is my first writer program. ");// exception
			fileWriter.flush();
			System.out.println("File written successfully");
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			
			try {
				if(null!=fileWriter) {
				fileWriter.close();  //may be nullPointer exception
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			};
		}
		
		
	}
	
	
	public void readFile(){
		
FileReader fileReader=null;
		
		try {

			fileReader=new  FileReader("c:\\javaprg\\filewrite.txt");
			BufferedReader bufferedReader=new BufferedReader(fileReader);
			 int b=0;
			   /* while ((b=fileReader.read())!=-1) {
			    	System.out.print((char) b);
					
				}*/
			 
			   String line=bufferedReader.readLine();
			    
			   while (null!=line) {
				   
				   System.out.println(line);
				   line=bufferedReader.readLine();				   
			}
			
			System.out.println("File read successfully");
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			
			try {
				if(null!=fileReader) {
				fileReader.close();  //may be nullPointer exception
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			};
		}
	}

	
	public void listFiles(){
		
		  File file=new File("c:\\javaprg\\");
		   
		   if(file.exists()){
			   
			   
			File fileList[]=   file.listFiles();
			   
			for (File fileDetails : fileList) {
				
				if(fileDetails.getName().indexOf(".class")!=-1){
					fileDetails.delete();
					System.out.println(fileDetails.getName()+" Deleted successfully");
				}
				System.out.println(fileDetails.getName());
				System.out.println(fileDetails.getAbsolutePath());
			}
			   
		   }else {
			   System.out.println("directory does not exist");
		   }
		
		
	}
}
